package com.heo.task.thread;

import org.apache.log4j.Logger;
import com.heo.task.CallBackTaskQueue;
import com.heo.util.HttpHelper;

public class CallBackThread implements Runnable {

	private static Logger logger = Logger.getLogger(CallBackThread.class);

	private CallBackInfo callBackInfo;

	public CallBackThread(CallBackInfo callBackInfo) {
		this.callBackInfo = callBackInfo;
	}

	public CallBackInfo getCallBackInfo() {
		return callBackInfo;
	}

	@Override
	public void run() {
		try {
			//第一次发送有休眠操作
			if(callBackInfo.getSleepTime() > 0 && callBackInfo.getReSendCount() == 0) {
				Thread.sleep(callBackInfo.getSleepTime());
			}
			callBackInfo.setReSendCount(callBackInfo.getReSendCount() + 1);
			callBackInfo.setLastSendTime(System.currentTimeMillis());
			boolean bool = sendCallBackTask(callBackInfo);
			logger.info("线程处理消息 = " + callBackInfo.getSendMessage() + ", 结果 = " + bool);
		} catch (Exception e) {
			logger.error("[回调]第" + callBackInfo.getReSendCount() + "，线程处理消息异常 = " + e.getMessage() + "，消息内容=" + callBackInfo.getSendMessage());
			if (callBackInfo.getReSendCount() < callBackInfo.getMaxReSendCount()) {
				CallBackTaskQueue.getInstance().addCallBackMsg(callBackInfo);
			}
		}
	}

	public boolean sendCallBackTask(CallBackInfo callBackInfo) throws Exception {
		logger.info(callBackInfo.getSendMessage() + "[回调]线程开始执行。");
		String sendContent = callBackInfo.getSendMessage();
		String httpUrl = callBackInfo.getSendUrl();
		String resultStr = null;
		if(httpUrl.equals("https")) {
			resultStr = HttpHelper.sendHttpPosts(httpUrl, sendContent);
		}else {
			resultStr = HttpHelper.sendHttpPost(httpUrl, sendContent);
		}
		logger.info("[回调]第" + callBackInfo.getReSendCount() + "次发起设备状态回调请求URL：" + httpUrl
				+ "　[参数内容]" + sendContent + "　[返回结果]" + resultStr);
		// 这里是同步响应的。所以对方需要马上告诉我是否收到。如果收到就不再重发。
		if ("success".equalsIgnoreCase(resultStr)) {
			return true;
		}else {
			throw new Exception("系统调用失败，进行下次回调，内容 = " + sendContent);
		}
	}

}
